package com.mrx.xfriendship.service;

import com.mrx.commons.annotations.XLog;
import com.mrx.xfriendship.kaptcha.impl.DefaultKaptcha;
import com.mrx.xfriendship.kaptcha.util.Config;
import lombok.SneakyThrows;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * @author Mr.X
 * @since 2023-01-14 11:26
 */
@XLog
@Service
@DubboService
public class CaptchaServiceImpl implements ICaptchaService {

    private static final Config config = Config.builder()
            .border(true)
            .borderColor("105,179,90")
            .textproducerFontColor("blue")
            .textproducerFontSize(100)
            .imageWidth(300)
            .imageHeight(100)
            .textproducerCharLength(4)
            .textproducerFontNames("宋体")
            .textproducerCharSpace(16)
            .noiseColor("blue")
            .textproducerCharString("0123456789")
            .build();

    private static final DefaultKaptcha captcha = new DefaultKaptcha(config);

    @Resource
    private IRedisService redisService;

    @Override
    @SneakyThrows(Throwable.class)
    public byte[] getCaptcha(String key) {
        String text = captcha.createText();
        BufferedImage image = captcha.createImage(text);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        // 将 验证码 保存 到 redis
        redisService.setCaptcha(key, text);
        return outputStream.toByteArray();
    }

    @Override
    public String getCaptchaStr(String key) {
        String text = captcha.createText();
        // 将 验证码 保存 到 redis
        redisService.setCaptcha(key, text);
        return text;
    }

    @Override
    public String getCaptchaStr() {
        return captcha.createText();
    }

    @Override
    public boolean verifyCaptcha(String key, String value) {
        return value.equals(redisService.getCaptcha(key));
    }

}
